const express = require("express");
const { ResponseBody } = require("../type");
const { getDatabase, getJsonBySheet, writeDataBase } = require("../database");
const { easyClassConstructor } = require("../util");

const convertMap = {
    name: "名称",
    startTime: "开始时间",
    endTime: "结束时间",
    content: "描述",
    belong: "归属",
};

class Era {
    constructor(parmas) {
        this.id = parmas.id;
        easyClassConstructor(this, parmas, convertMap);
    }
}

const router = express.Router();

router.get("/get", (req, res) => {
    getDatabase("era")
        .then((data) => {
            const sheet = data.Sheets[data.SheetNames[0]];
            const source =
                getJsonBySheet(sheet)?.map((item) => new Era(item)) ?? [];
            const ret = source.filter((item) => !item.belong);
            const ages = source.filter((item) => item.belong);
            const erasMap = new Map();
            ret.forEach((item) => {
                erasMap.set(item.name, item);
                item.children = [];
            });
            ages.forEach((item) => {
                if (erasMap.has(item.belong)) {
                    erasMap.get(item.belong)?.children.push(item);
                }
            });
            res.json(new ResponseBody(ret));
        })
        .catch((err) => {
            res.json(new ResponseBody([], 400, "时代请求错误" + err));
        });
});

module.exports = router;
